<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;
use yii\helpers\ArrayHelper;

use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;

use app\models\HistoryModel;

class HistoryController extends Controller
{

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
    public function actionAdd()
    {
        $openid = Yii::$app->request->post('openid');
        $code = Yii::$app->request->post('code');
        $examname = Yii::$app->request->post('examname');
        $questions = Yii::$app->request->post('questions');
        $answers = Yii::$app->request->post('answers');
        $records = Yii::$app->request->post('records');
        $score = Yii::$app->request->post('score');
 
        // Yii::$app->db->createCommand()->insert('message',[
        //     'image'=>$image,
        //     'title'=>$title,
        //     'content'=>$content
        //     ])->execute();

        // 新建一条记录
        $model = new HistoryModel;
        $model->openid = $openid;
        $model->code = $code;
        $model->examname = $examname;
        $model->questions = $questions;
        $model->answers = $answers;
        $model->records = $records;
        $model->score = $score;
        
        $model->save();
        
        $id =$model->id;
        $model = HistoryModel::find()
            ->where(['id' => $id])
            ->orderBy('id DESC')
            ->asArray()
            ->one();

        $data = array(
            'code' => 0,
            'message' => '新增成功',
            'result' => $model
        );
        $json = json_encode($data);
        return $json;
    }
    public function actionGetitems()
    {
        $model = HistoryModel::find()
            ->asArray()
            ->all();

        $json = json_encode($model);
        return $json;
    }
    public function actionGetbyopenid()
    {
        $openid = Yii::$app->request->post('openid');
        $model = HistoryModel::find()
            ->where(['openid' => $openid])
            ->orderBy('id DESC')
            ->asArray()
            ->all();

        $data = array(
            'code' => 0,
            'message' => '',
            'result' => $model
        );

        $json = json_encode($data);
        return $json;
    }
    public function actionGetjsonbyid()
    {
        $qid = Yii::$app->request->get('id');
        $model = HistoryModel::find()
            ->select(['code', 'content', 'value'])
            ->where(['qid' => $qid])
            ->orderBy('id ASC')
            ->asArray()
            ->all();

        $json =  json_encode($model, JSON_UNESCAPED_UNICODE);
        echo($json);
    }    
}
